import React, { useState, useEffect, useMemo, useContext, useRef } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button,
  Space,
  Popover,
  Checkbox,
  Modal,
  Message,
  Typography,
} from '@arco-design/web-react';
import { IconFilter, IconPlus } from '@arco-design/web-react/icon';
import cs from 'classnames';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { getColumns } from './constants';
import { GlobalContext } from '@/context';
import Create from './create';
import ActionWrapper from '@/components/ActionWrapper';
import useIsMountedRef from '@/utils//useIsMountedRef';
import { Delete, Search } from '@/api/modules/deviceManager';
import { DeviceCreate } from '@/api/interface/deviceManager';
import useStorageJson from '@/utils/useStorageJson';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
import debounce from 'lodash/debounce';
import has from 'lodash/has';
import isEmpty from 'lodash/isEmpty';
const { Title } = Typography;

function DeviceManager() {
  const t = useLocale(locale);
  const { rtl, lang } = useContext(GlobalContext);
  const { userInfo } = useSelector((state: GlobalState) => state);
  const [tableColumns, setTableColumns] = useStorageJson(
    `${userInfo.id}_deviceManager_tableColumns`,
    ['id', 'uuid', 'remark', 'action']
  );
  const options = [
    {
      label: t['searchTable.columns.number'],
      value: 'id',
      width: 60,
    },
    {
      label: t['searchTable.columns.uuid'],
      value: 'uuid',
    },
    {
      label: t['searchTable.columns.remark'],
      value: 'remark',
    },
    {
      label: t['searchTable.columns.action'],
      value: 'action',
    },
  ];

  const [visible, setVisible] = useState(false);
  const onVisible = (status: boolean, refresh?: boolean) => {
    setVisible(status);
    if (refresh) {
      if (pagination.current === 1) {
        fetchData();
        return;
      }
      setPatination({ ...pagination, current: 1 });
    }
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(false);
  const [formParams, setFormParams] = useState({});
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  useEffect(() => {
    tableRef.current = {
      pageSize: pagination.pageSize,
      total: pagination.total,
      current: pagination.current,
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.total, pagination.pageSize, pagination.current]);

  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const { data } = await Search({
        pageNo: current,
        pageSize,
        ...formParams,
      });
      if (isMountedRef.current) {
        setData(data.data);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: data.count,
        });

        setLoading(false);
      }
    } catch (e) {
      console.log(e);
      setLoading(false);
    }
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const handleSearch = debounce((params) => {
    if (has(params, 'active')) {
      params.active =
        params.active === 1 ? true : params.active === 0 ? false : '';
    }
    if (loading && isEmpty(params)) return;
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }, 300);

  const CheckboxGroup = Checkbox.Group;

  const tableColumnsFilter = () => (
    <CheckboxGroup
      direction="vertical"
      options={options.map((a) => {
        let disabled = false;
        if (tableColumns.length === 1) {
          disabled = tableColumns.includes(a.value);
        }

        return { ...a, disabled };
      })}
      value={tableColumns}
      onChange={(value) => {
        if (value.length < 1) {
          return;
        }
        setTableColumns(value);
      }}
    />
  );

  const [modalStatus, setMldalStatus] = useState<boolean>(false);
  const [modalLoading, setModalLoading] = useState<boolean>(false);
  const [record, setRecord] = useState<Partial<DeviceCreate>>({
    id: '',
    remark: '',
    uuid: '',
    createdAt: null,
    orgId: null,
  });
  const tableCallback = async (record: any, type: string) => {
    if (type === 'remove') {
      setMldalStatus(true);
      setRecord(record);
      return;
    }
  };

  const tableRef = useRef({ pageSize: 0, total: 0, current: 0 });

  const columns = useMemo(
    () => getColumns(t, tableCallback, tableColumns, options, lang),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t, tableColumns]
  );
  return (
    <Card>
      {/* <Title heading={6} className={styles['page-title']}>
        {t['searchTable.form.title']}
      </Title> */}
      <SearchForm onSearch={handleSearch} />

      <Create visible={visible} onVisible={onVisible} />
      <div className={cs(styles['button-group'], rtl ? 'rtl' : '')}>
        <Space>
          <ActionWrapper action="devicemanager.device/create">
            <Button
              type="primary"
              icon={<IconPlus />}
              onClick={() => setVisible(true)}
            >
              {t['searchTable.operations.add']}
            </Button>
          </ActionWrapper>
        </Space>
        <Space>
          <Popover
            position="bottom"
            trigger="click"
            content={tableColumnsFilter}
          >
            <Button icon={<IconFilter />}>
              {t['searchTable.operation.filter']}
            </Button>
          </Popover>
        </Space>
      </div>
      <Table
        border={{
          wrapper: true,
          cell: true,
        }}
        hover={true}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />

      <Modal
        className={cs(rtl ? 'rtl' : '')}
        confirmLoading={modalLoading}
        closable
        style={{ width: '760px' }}
        title={<>{t['modal.remove.title']}</>}
        visible={modalStatus}
        simple
        okText={t['modal.remove']}
        onOk={() => {
          setModalLoading(true);
          Delete(record.id)
            .then(() => {
              Message.success(t['modal.remove.success']);
              setMldalStatus(false);
              setModalLoading(false);
              fetchData();
            })
            .catch(() => {
              setModalLoading(false);
            });
        }}
        onCancel={() => {
          setMldalStatus(false);
        }}
      >
        <div className={styles['modal-content']}>
          {t['modal.remove.desc']}
          <span style={{ fontWeight: 'bold', color: '#ff4000' }}>
            {' "'}
            {record.uuid} {record.remark && `(${record.remark})`}
            {'"'}
          </span>
          ?
        </div>
      </Modal>
    </Card>
  );
}

export default DeviceManager;
